package com.namo.cchapi.service.impl;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.namo.cchapi.config.BaiduAiConfig;
import com.namo.cchapi.entity.FaceEntity;
import com.namo.cchapi.service.FaceService;
import com.namo.cchcommon.api.CommonResult;
import com.namo.cchcommon.api.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.nio.charset.CoderResult;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author WangXin
 * @date 2021/3/31 21:22
 */
@Service
@Slf4j
@RefreshScope
public class FaceServiceImpl implements FaceService {

    @Value("${baidu.face.group-id}")
    private String groupId;

    @Autowired
    AipFace aipFace;

    @Autowired
    Gson gson;

    private static final String RESULT = "result";
    private static final String SCORE = "score";
    /**
     * 识别阈值
     */
    private static final Double LOW_SCORE = 80.0;


    @Override
    public CommonResult addFace(String faceUrl, String userId) {
        // 用户信息查询
        JSONObject res = aipFace.getUser(userId, groupId, new HashMap<String, String>());
        if (res.get("result").equals(null) == true) {
            // 人脸注册
            JSONObject addRes = aipFace.addUser(faceUrl, "URL", groupId, userId, new HashMap<String, String>());
            if (addRes.get("result").equals(null) == true) {
                return CommonResult.failed(ResultCode.FAILED, addRes.get("error_msg").toString());
            }
            FaceEntity faceEntity = new FaceEntity();
            faceEntity.setFaceUrl(faceUrl);
            faceEntity.setUserId(userId);
            faceEntity.setGroupId(groupId);
            faceEntity.setFaceToken(addRes.getJSONObject("result").get("face_token").toString());
            log.info("添加人脸成功：" + faceEntity.toString());
            return CommonResult.success(faceEntity);
        } else {
            FaceEntity faceEntity = new FaceEntity();
            faceEntity.setUserId(userId);
            faceEntity.setGroupId(groupId);
            faceEntity.setFaceUrl(faceUrl);
            // 获取用户人脸列表
            JSONObject faceListRes = aipFace.faceGetlist(userId, groupId, new HashMap<>());
            faceEntity.setFaceToken(faceListRes.getJSONObject("result").getJSONArray("face_list").getJSONObject(0).get("face_token").toString());
            log.info("人脸已经存在：" + faceEntity.toString());
            return CommonResult.success(faceEntity);
        }
    }

    /**
     * 人脸对比
     * @param image1
     * @param image2
     * @return
     * @throws Exception
     */
    @Override
    public Boolean matchFace(String image1, String image2) throws Exception {
        //构造人脸集合
        ArrayList<MatchRequest> matchRequests = new ArrayList<>();
        MatchRequest matchRequest1 = new MatchRequest(image1, "URL");
        MatchRequest matchRequest2 = new MatchRequest(image2, "URL");
        matchRequests.add(matchRequest1);
        matchRequests.add(matchRequest2);
        JSONObject match = aipFace.match(matchRequests);
        JsonObject jsonObject = gson.fromJson(match.toString(), JsonObject.class);
        if (jsonObject.getAsJsonObject(RESULT).has(SCORE) == false) {
            throw new Exception("识别失败");
        }
        Double score = jsonObject.getAsJsonObject(RESULT).get(SCORE).getAsDouble();
        log.info("对比得分："+score.toString());
        if (score <= LOW_SCORE){
            return false;
        }
        return true;
    }
}
